<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>奕彩SSQ</title>
    <!-- CSS only -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet"
        async="async">
    <style>
        .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            user-select: none;
        }

        @media (min-width: 576px) {
            .row-cols-sm-2>* {
                flex: 0 0 auto;
                width: 100%;
            }
        }
        @media (min-width: 768px) {
            .bd-placeholder-img-lg {
                font-size: 3.5rem;
            }
            .row-cols-sm-2>* {
                flex: 0 0 auto;
                width: 50%;
            }
        }
        @media (min-width: 992px) {
            .row-cols-md-3>* {
                flex: 0 0 auto;
                width: 33.3333333333%;
            }
        }

        .ocr-ssq-item {
            min-width: 285px;
        }

        .ocr-ssq-item h6 {
            text-align: left;
        }

        .ocr-ssq-item .card-text span {
            font-size: 12px;
            padding: 1px;
            font-family: monospace;
        }

        .ocr-ssq-item .red {
            color: black;
            border: 1px solid red;
        }

        .ocr-ssq-item .blue {
            color: black;
            border: 1px solid #0d6efd;
        }

        .ocr-ssq-item .err {
            color: #fff;
            background-color: black;
            border: 1px solid black;
        }

        .ocr-ssq-item .redf {
            color: #fff;
            background-color: red;
            border: 1px solid red;
        }

        .ocr-ssq-item .bluef {
            color: #fff;
            background-color: #0d6efd;
            border: 1px solid #0d6efd;
        }

        .ssq-item .red {
            color: #fff;
            background-color: red;
            border-color: red;
            border-radius: 25px;
            padding: 5px;
            font-family: monospace;
        }

        .ssq-item .blue {
            color: #fff;
            background-color: #0d6efd;
            border-color: #0d6efd;
            border-radius: 25px;
            padding: 5px;
            font-family: monospace;
        }

        .ssq-item {
            min-width: 300px;
        }

        .ssq-item .shadow-sm {
            min-width: 285px;
        }

        .upload-box1 {
            min-width: 285px;
            width: 100%;
            height: 50px;
            border: 1px dashed;
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ctext x='50%25' y='50%25' font-size='18' fill='%236699ff' text-anchor='middle' dominant-baseline='middle'%3E图片识别%3C/text%3E%3C/svg%3E") no-repeat center;
        }

        .upload-box1[disabled] {
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ctext x='50%25' y='50%25' font-size='18' fill='%23A9A9A9' text-anchor='middle' dominant-baseline='middle'%3E正在处理%3C/text%3E%3C/svg%3E") no-repeat center;
        }

        .upload-box1[init] {
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ctext x='50%25' y='50%25' font-size='18' fill='%23A9A9A9' text-anchor='middle' dominant-baseline='middle'%3E初始化中%3C/text%3E%3C/svg%3E") no-repeat center;
        }

        #dataBody .card-body {
            padding: 2px;
        }

        #dataBody .shadow-sm {
            box-shadow: none !important;
            border: none;
        }
    </style>
</head>

<body>
    <main>

        <section class="py-4 text-center container">
            <div class="row py-lg-2">
                <div class="col-lg-6 col-md-8 mx-auto">
                    <div class="mb-3">
                        <input style="display: none;" class="form-control" type="file" accept="image/*" id="input-img">
                        <button id="up-btn" class="upload-box1" disabled init></button>
                    </div>
                    <div id="dataBody" class="ocr-ssq-item">


                    </div>
                </div>
            </div>
        </section>

        <div class="album py-1">
            <div class="container">
                <h5 style="text-align: center">历史开奖信息</h5>
                <h6 style="text-align: center" id="data-update-time"></h6>
                <div id="ssq-el" class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
                    <!-- <div th:each="ssq : ${ssqList}" class="col ssq-item">
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted"><span th:text="${ssq.code}"></span> 期</h6>
                            <h6 class="card-text">
                                <span th:text="${ssq.red1}" class="red"></span>
                                <span th:text="${ssq.red2}" class="red"></span>
                                <span th:text="${ssq.red3}" class="red"></span>
                                <span th:text="${ssq.red4}" class="red"></span>
                                <span th:text="${ssq.red5}" class="red"></span>
                                <span th:text="${ssq.red6}" class="red"></span>
                                <span th:text="${ssq.blue1}" class="blue"></span>
                            </h6>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">开奖日期：<span th:text="${ssq.drawDate}"></span></small>
                            </div>
                        </div>
                    </div>
                </div> -->

                </div>
            </div>
        </div>


    </main>
</body>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"
    async="async"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/tesseract.js@4/dist/tesseract.min.js'></script>
<script src='https://cdn.bootcdn.net/ajax/libs/compressorjs/1.2.1/compressor.min.js' async="async"></script>
<script>
    var dataUrl = 'https://100180.xyz/ssq/data/ssq.txt';
    var ssqList = [];
    var ssqMap = {};
    var lastIndex = 0;
    var dbj = 5;
    var language = "eng"
    var bel = $("#dataBody");

    var testImg = ``;
    var loadImg = `<img src="https://cdn.jsdelivr.net/gh/midaug/files/static/images/loading.gif" />`;
    function loadSsqEl(lists, last) {
        var ssqEl = $("#ssq-el");
        for (let i = 0; i < lists.length; i++) {
            var ssqCode = lists[i];
            var ssq = ssqMap[ssqCode];
            var htmlStr = `<div class="col ssq-item">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-2 text-muted"><span>${ssq.code}</span> 期</h6>
                        <h6 class="card-text">
                            <span class="red">${ssq.red1}</span>
                            <span class="red">${ssq.red2}</span>
                            <span class="red">${ssq.red3}</span>
                            <span class="red">${ssq.red4}</span>
                            <span class="red">${ssq.red5}</span>
                            <span class="red">${ssq.red6}</span>
                            <span class="blue">${ssq.blue1}</span>
                        </h6>
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">开奖日期：<span>${ssq.drawDate}</span></small>
                        </div>
                    </div>
                </div>
            </div> `
            ssqEl.append(htmlStr);
        }
        lastIndex = last;
    }

    function formatDateTime(inputTime) {
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        var h = date.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? "0" + minute : minute;
        second = second < 10 ? "0" + second : second;
        return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    }
    $(document).ready(function () {
        bel.html(loadImg);
        function scrollLoad(bj) {
            var s = lastIndex;
            var e = lastIndex + bj > ssqList.length ? ssqList.length : lastIndex + bj;
            var newArr = ssqList.slice(s, e);
            loadSsqEl(newArr, e);
        }
        function loadSsqData() {
            console.log(window.ssqData);
            $.get(dataUrl + "?v=" + new Date().getTime(), function (data) {
                var arr = data.split("\n");
                $("#data-update-time").html(formatDateTime(parseInt(arr[0].split(",")[3])));
                for (let i = 1; i < arr.length; i++) {
                    var ssqArr = arr[i].split(",");
                    if (!ssqArr[0]) {
                        continue;
                    }
                    var code = "20" + ssqArr[0];
                    obj = {
                        "code": code,
                        "red1": ssqArr[1],
                        "red2": ssqArr[2],
                        "red3": ssqArr[3],
                        "red4": ssqArr[4],
                        "red5": ssqArr[5],
                        "red6": ssqArr[6],
                        "blue1": ssqArr[7],
                        "bonus1": ssqArr[8],
                        "bonus2": ssqArr[9],
                        "drawDate": ssqArr[10]
                    };
                    ssqList.push(code);
                    ssqMap[code] = obj;
                }
                scrollLoad(30);
                //初始化
                const t0 = window.performance.now();
                Tesseract.recognize(
                    testImg, language,
                    {
                        workerPath: 'https://cdn.jsdelivr.net/npm/tesseract.js@4/dist/worker.min.js',
                        langPath: 'https://cdn.jsdelivr.net/gh/midaug/files/static/tesseract.js/lang/4.0.0',
                        corePath: 'https://cdn.jsdelivr.net/npm/tesseract.js-core@4',
                        // logger: m => console.log(m)
                    }
                ).catch(err => {
                    console.error(err);
                }).then(result => {
                    const t1 = window.performance.now();
                    console.log("init Tesseract.js", t1 - t0, result);
                    if (result && result.data && result.data.text) {
                        $("#up-btn").removeAttr("disabled");
                        $("#up-btn").removeAttr("init");
                        bel.html("");
                    }
                });
            });
        }
        loadSsqData();
        $(window).scroll(function () {
            if ($(document).scrollTop() + $(window).height() >= $(document).height() - 50) {
                scrollLoad(dbj);
            }
        });
    });

    //////////////////

    function vNum(num, s, e) {
        if (isNaN(num)) return false;
        var n = parseInt(num);
        return n >= s && n <= e;
    }
    //渲染识别结果
    function updateOcrData(data, rc) {
        var title = '<h6 class="card-subtitle mb-2 text-muted"><span>' + data.code + '</span>期 开奖日期: ' + data.drawDate + '</h6>';
        var tags = ['<div class="card shadow-sm"><div class="card-body">', title];
        for (var i in data.noteDtos) {
            tags.push('<h6 class="card-text">');
            var note = data.noteDtos[i];
            tags.push('<span>' + note['zm'] + '</span>');
            for (var num = 1; num <= 6; num++) {
                var key = 'red' + num;
                var keyf = 'red' + num + 'f';
                var cls = note[keyf] ? 'num red redf' : 'num red';
                cls = vNum(note[key], 1, 33) ? cls : 'num err';
                tags.push('<span class="' + cls + '">' + note[key] + '</span>');
            }
            var cls = note['blue1f'] ? 'num blue bluef' : 'num blue';
            cls = vNum(note['blue1'], 1, 16) ? cls : 'num err';
            tags.push('<span class="' + cls + '">' + note['blue1'] + '</span>');
            tags.push('<span>' + note['reward'] + '</span>');
            tags.push('<span>' + note['bonus'] + '</span>');
            tags.push('</h6>');

        }

        tags.push('<h6 class="card-subtitle mb-2 text-muted" style="font-size: 0.75rem; margin-top: 1rem;">压缩耗时: ' + rc["压缩耗时"] + '</h6>');
        tags.push('<h6 class="card-subtitle mb-2 text-muted" style="font-size: 0.75rem;">压缩前大小: ' + rc["压缩前大小"] + '</h6>');
        tags.push('<h6 class="card-subtitle mb-2 text-muted" style="font-size: 0.75rem;">压缩后大小: ' + rc["压缩后大小"] + '</h6>');
        tags.push('<h6 class="card-subtitle mb-2 text-muted" style="font-size: 0.75rem;">压缩比: ' + rc["压缩比"] + '</h6>');
        tags.push('<h6 class="card-subtitle mb-2 text-muted" style="font-size: 0.75rem;">识别耗时: ' + rc["识别耗时"] + '</h6>');
        tags.push('</div></div>');
        bel.html(tags.join('\n'));
        $("#up-btn").removeAttr("disabled");
    }

    function zzpp(str, zzs) {
        for (var i = 0; i < zzs.length; i++) {
            var e = zzs[i];
            var vs = str.match(e);
            if (vs && vs.length > 0) {
                return vs[0];
            }
        }
    }
    //识别期号
    function zzppCode(txt) {
        var code = zzpp(txt, [/20[012]\d{4}-\d{3}/g]);
        if (code) {
            return code.split("-")[0];
        }
        return zzpp(txt, [/20[012]\d{4}/g]);
    }
    //匹配中奖
    function ppzj(ssqData, hm) {
        var reds = [ssqData.red1, ssqData.red2, ssqData.red3, ssqData.red4, ssqData.red5, ssqData.red6]
        var zm = hm.slice(0, 1);
        var red1 = hm.slice(1, 3);
        var red2 = hm.slice(3, 5);
        var red3 = hm.slice(5, 7);
        var red4 = hm.slice(7, 9);
        var red5 = hm.slice(9, 11);
        var red6 = hm.slice(11, 13);
        var blue1 = hm.slice(13, 15);
        var data = {
            "code": ssqData.code,
            "red1": red1,
            "red2": red2,
            "red3": red3,
            "red4": red4,
            "red5": red5,
            "red6": red6,
            "blue1": blue1,
            "drawDate": ssqData.drawDate,
            "red1f": false,
            "red2f": false,
            "red3f": false,
            "red4f": false,
            "red5f": false,
            "red6f": false,
            "blue1f": false,
            "reward": "无",
            "bonus": "0",
            "zm": zm
        }

        var redNum = 0;
        for (let i = 1; i <= 6; i++) {
            if (reds.indexOf(data["red" + i]) > -1) {
                data["red" + i + "f"] = true;
                redNum++;
            }
        }
        if (data["blue1"] == ssqData["blue1"]) {
            data["blue1f"] = true;
        }
        if (redNum == 6 && data["blue1f"]) {
            data["reward"] = "一等奖";
            data["bonus"] = ssqData["bonus1"];
        } else if (redNum == 6) {
            data["reward"] = "二等奖";
            data["bonus"] = ssqData["bonus2"];
        } else if (redNum == 5 && data["blue1f"]) {
            data["reward"] = "三等奖";
            data["bonus"] = "3000";
        } else if (redNum == 5 || (redNum == 4 && data["blue1f"])) {
            data["reward"] = "四等奖";
            data["bonus"] = "200";
        } else if (redNum == 4 || (redNum == 3 && data["blue1f"])) {
            data["reward"] = "五等奖";
            data["bonus"] = "10";
        } else if (data["blue1f"]) {
            data["reward"] = "六等奖";
            data["bonus"] = "5";
        }
        return data;
    }

    //开始解析
    // Bevk: W ER- LIRS 31050671
    // 6E15-5806-F294-CAF6-C1B9/63707293/56CC1
    // A.04 07 16 23 25 29-16 (1
    // B.06 15 16 17 21 26-12 (1
    // C.01 05 11 26 30 31-05 (1
    // D.06 13 19 22 26 32-07 (1
    // E.08 12 26 27 30 32-13 (1
    // F1 40 2022082 22-07-19 air10,¢
    // 4801 2022082-115 22-07-18 20:47:49 i
    // JH 2R 14892
    // TR N2 25 R4 S0 HTNR3 . 60 U1

    function ocrSsq(txt, rc) {
        console.log(txt);
        //提取期号
        var code = zzppCode(txt);
        if (!code) {
            bel.html("找不到期号！ <br>" + txt);
            $("#up-btn").removeAttr("disabled");
            return;
        }
        var ssqData = ssqMap[code];
        if (!ssqData) {
            bel.html("期号识别错误！-> " + code);
            $("#up-btn").removeAttr("disabled");
            return;
        }
        console.log(code, ssqData);
        var zjData = {
            code: code,
            drawDate: ssqData.drawDate
        }
        //删除大写字母和数字以外的字符
        var nTxt = txt.replace(/[^A-Z0-9]/gi, '');
        console.log(nTxt);
        //按A[0-9]{14}类似的规则提取号码
        var a = zzpp(nTxt, [/A[0-9]{14}/g]);
        var b = zzpp(nTxt, [/B[0-9]{14}/g]);
        var c = zzpp(nTxt, [/C[0-9]{14}/g]);
        var d = zzpp(nTxt, [/D[0-9]{14}/g]);
        var e = zzpp(nTxt, [/E[0-9]{14}/g]);
        console.log(a, b, c, d, e);
        //匹配是否中奖
        var noteDtos = [];
        if (a) {
            noteDtos.push(ppzj(ssqData, a));
        }
        if (b) {
            noteDtos.push(ppzj(ssqData, b));
        }
        if (c) {
            noteDtos.push(ppzj(ssqData, c));
        }
        if (d) {
            noteDtos.push(ppzj(ssqData, d));
        }
        if (e) {
            noteDtos.push(ppzj(ssqData, e));
        }
        zjData["noteDtos"] = noteDtos;
        updateOcrData(zjData, rc);
    }

    ///////////

    $("#up-btn").click(function () {
        $("#input-img").click();
        // ocrSsq(`
        // Bevk: W ER- LIRS 31050671
        // 6E15-5806-F294-CAF6-C1B9/63707293/56CC1
        // A.04 07 16 23 25 29-16 (1
        // B.06 15 16 17 21 26-12 (1
        // C.01 05 11 26 30 31-05 (1
        // D.06 13 19 22 26 32-07 (1
        // E.08 12 26 27 30 32-13 (1
        // F1 40 2022082 22-07-19 air10,¢
        // 4801 2022082-115 22-07-18 20:47:49 i
        // JH 2R 14892
        // TR N2 25 R4 S0 HTNR3 . 60 U1
        // `);
    });

    function formatBytes(a, b = 2, k = 1024) { with (Math) { let d = floor(log(a) / log(k)); return 0 == a ? "0 Bytes" : parseFloat((a / pow(k, d)).toFixed(max(0, b))) + " " + ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"][d] } }

    function recognizeFile(file) {
        $("#up-btn").attr("disabled", 'disabled');
        const t0 = window.performance.now();
        bel.html(loadImg);
        new Compressor(file, {
            quality: 0.9,
            maxWidth: 1280,
            success: function (newFile) {
                const t1 = window.performance.now();
                const rc = {
                    "压缩耗时": ((t1 - t0) / 1000).toFixed(3) + "秒",
                    "压缩前大小": formatBytes(file.size),
                    "压缩后大小": formatBytes(newFile.size),
                    "压缩比": (newFile.size / file.size * 100).toFixed(2) + "%"
                };
                Tesseract.recognize(
                    newFile, language,
                    {
                        workerPath: 'https://cdn.jsdelivr.net/npm/tesseract.js@4/dist/worker.min.js',
                        langPath: 'https://cdn.jsdelivr.net/gh/midaug/files/static/tesseract.js/lang/4.0.0',
                        corePath: 'https://cdn.jsdelivr.net/npm/tesseract.js-core@4',
                        // logger: m => console.log(m)
                    }
                ).catch(err => {
                    console.error(err);
                    $("#up-btn").removeAttr("disabled");
                }).then(result => {
                    rc["识别耗时"] = ((window.performance.now() - t1) / 1000).toFixed(3) + "秒";
                    // bel.html(result.data.text);
                    console.log(rc);
                    ocrSsq(result.data.text, rc);
                });
            },
            error(err) {
                console.error(err);
                $("#up-btn").removeAttr("disabled");
            },
        });

    }
    $("#input-img").change(function (e) {
        recognizeFile(this.files[0]);
    });
</script>

</html>